R4DS 16 - Vectors
The codes below are from the practice exercises in https://r4ds.had.co.nz/, and are taken with reference from: https://jrnold.github.io/r4ds-exercise-solutions/
Loading tidyverse package.
There are two types of vectors:
# use the set_names function
purrr::set_names(1:3, nm = letters[1:3])
a b c
1 2 3
dplyr::filter() only works for tibbles.
[1] "three" "two" "five"
x[c(2,2,4,4,5)]
[1] "two" "two" "four" "four" "five"
# subsetting with named vectors
a <- set_names(1:10, # vectors
letters[1:10]) # names
a
a b c d e f g h i j
1 2 3 4 5 6 7 8 9 10
# specify what to be subsetted
a[c("d", "e", "j")]
d e j
4 5 10
Create a function that takes a vector as input and returns the last value.
[1] 1 3 5 7 9
length(x) # 5
[1] 5
x[[length(x)]] # returns the last value by subsetting it out as single element
[1] 9
# put as function
last_value <- function(x) {
# check for case with no length
if(length(x)) {
x[[length(x)]]
}
else {
x
}
}
last_value(x)
[1] 9
Create a function that take a vector as input and returns the elements at even numbered positions
x
[1] 1 3 5 7 9
# put as function
even_indices <- function(x) {
# check for case with no length
if(length(x)) {
x[seq_along(x) %% 2 == 0]
}
else {
x
}
}
even_indices(x)
[1] 3 7
Lists can contain other lists. Lists can contain a mixture of objects.
$a
[1] 1 2 3
$b
[1] "a string"
$c
[1] 3.141593
$d
$d[[1]]
[1] -1
$d[[2]]
[1] -5
# subset a list using [ ]
a[1:2] # first two items of the list
$a
[1] 1 2 3
$b
[1] "a string"
# subset a single component of the list using [[ ]]
str(a[[4]]) # goes into the list item 4
List of 2
$ : num -1
$ : num -5
a[[4]][1] # list item 4, first number
[[1]]
[1] -1
# using $ to extract names elements of the list
a$a
[1] 1 2 3
The main takeaway that I had from this chapter is how to name vectors to subset them (using [ ]), and how to use different ways to subset lists (using [ ], [[ ]], $)
https://jrnold.github.io/r4ds-exercise-solutions/
For attribution, please cite this work as
lruolin (2021, May 26). pRactice corner: Vectors. Retrieved from https://lruolin.github.io/myBlog/posts/20210526_Tidyverse Chap 16 - Vectors/
BibTeX citation
@misc{lruolin2021vectors, author = {lruolin, }, title = {pRactice corner: Vectors}, url = {https://lruolin.github.io/myBlog/posts/20210526_Tidyverse Chap 16 - Vectors/}, year = {2021} }